package com.apes.fn.scm.commodityInquiry.model;

import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.*;


/**
 * 外采询价单
 */


@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = ExternalInquiry.CONST_TABLE_NAME)
public class ExternalInquiry extends Model {
    public static final String CONST_TABLE_NAME = "pur_external_inquiry";

    /***
     * WX12 OR WC12
     */

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "外采询价单", prefix = "WC12", padding = 8)
    @Comment("询价单号")
    private String id;

    @Column(name = "source_business_type", nullable = false)
    @Comment("来源单据类型")
    private String sourceBusinessType;

    @Column(name = "source_business_type_name", nullable = false)
    @Comment("来源单据类型")
    private String sourceBusinessTypeName;

    @Column(name = "source_business_key", nullable = false)
    @Comment("来源单据号码")
    private String sourceBusinessKey;


    @Transient
    private String sourceBusiness;

    public String getSourceBusiness() {
        if (sourceBusinessKey == null || sourceBusinessTypeName == null) return null;
        return "[" + sourceBusinessTypeName + "]" + sourceBusinessKey;
    }

    @States(name = "单据状态", values = {
            @State(id = "transApprove", name = "转审核"),
            @State(id = "backInquiry", name = "退回"),
            @State(id = "waitConfirm", name = "待确认"),
            @State(id = "approve", name = "审核"),
            @State(id = "cancel", name = "取消")})
    @Column(name = "state", nullable = false)
    @Comment("单据状态")
    private String state;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("门店编码")
    private Dept dept;

    @Comment("公司")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    private PartyRole company;

    @Comment("会员扩展信息")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
    private FnCustomerExpand customerExpand;

    @Column(name = "note", length = 4000)
    @Comment("备注")
    private String remark;

    /***
     * 供应商默认为[004465] 赋能门店现金外采
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商")
    private PartyRole supplier;

    /***
     * 平台默认为1007
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "platform_id", referencedColumnName = "id")
    @Comment("平台")
    private PartyRole platform;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cancel_id", referencedColumnName = "id")
    @Comment("取消人")
    private PartyRole cancelId;

    @Column(name = "cancel_date")
    @Comment("取消日期")
    private Date cancelDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "back_id", referencedColumnName = "id")
    @Comment("退回人")
    private PartyRole backId;

    @Column(name = "back_date")
    @Comment("退回日期")
    private Date backDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_id", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveId;

    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "answer_id", referencedColumnName = "id")
    @Comment("响应人")
    private PartyRole answerId;

    @Column(name = "answer_date")
    @Comment("响应时间")
    private Date answerDate;

    @Comment("门店节点候选人")
    @Column(name = "next_dispose_sign", length = 120)
    private String nextDisposeSign;

    @Transient
    private Map customerCar;
    public Map getCustomerCar() {
        if (customerExpand == null) return null;
        return MapUtil.mapper(
                "PZCXID", customerExpand.getJekunModelCode(),
                "PZCXMC", customerExpand.getCarModelLabel(),
                "CJHM", customerExpand.getVin(),
                "CPHM", customerExpand.getCarLicense()
        );
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if(this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

    @OneToMany(mappedBy = "externalInquiry", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<ExternalInquiryItem> externalInquiryItems = new ArrayList<>();

    public List<ExternalInquiryItem> getExternalInquiryItems() {

        for (ExternalInquiryItem item : externalInquiryItems) {
            item.setExternalInquiry(this);
        }
        return externalInquiryItems;
    }

    @Transient
    private Boolean hide = true;

    @Transient
    public Boolean getHide() {
        if("backInquiry".equals(this.state)) return false;
        return !StringUtils.isEmpty(this.externalInquiryItems.get(0).getInquiryReason());
    }

    @Transient
    private String outsourcingApproval;

    public String getOutsourcingApproval() {
        Store store = SpringManager.getBean(StoreRepository.class).findByDept(this.dept);
        if (Objects.isNull(store.getOutsourcingApproval())) throw new RuntimeException("请联系采购在【门店信息】界面设置 【配置外采审批】, 门店: " + store.getName());
        return store.getOutsourcingApproval().getId();
    }
}
